<template>
  <div class="echarts-card">
    <div class="card-header" v-if="title">
      <span class="title">{{ title }}</span>
      <slot name="header-right"></slot>
    </div>
    <div class="chart-container" ref="chart" :style="{ height: chartHeight }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'EchartsCard',
  props: {
    title: {
      type: String,
      default: ''
    },
    options: {
      type: Object,
      required: true
    },
    height: {
      type: [String, Number],
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    chartHeight() {
      if (typeof this.height === 'number') {
        return `${this.height}px`
      }
      return this.height
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption(this.options)
    }
  },
  watch: {
    options: {
      handler(val) {
        this.chart && this.chart.setOption(val)
      },
      deep: true
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  }
}
</script>

<style scoped>
.echarts-card {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  height: 100%;
  display: flex;
  flex-direction: column;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.title {
  font-size: 16px;
  font-weight: bold;
}
.chart-container {
  flex: 1;
  min-height: 0;
}
</style> 